package com.zwf.utils;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.springframework.beans.factory.annotation.Value;

import java.util.ArrayList;
import java.util.List;

public class FileUtils {
    @Value("${uploadPath}")
    private String uploadPath;

    public static List<List<String>> readExcel(Sheet sheet) {
        List<List<String>> tableData = new ArrayList<>();
        for(Row row : sheet) {
            List<String> rowData = new ArrayList<>();
            for (Cell cell : row) {
                if (cell != null) {
                    CellType type = cell.getCellType();
                    switch(type) {
                        case STRING:
                            rowData.add(cell.getStringCellValue());
                            break;
                        case NUMERIC:
                            rowData.add(String.valueOf(cell.getNumericCellValue()));
                            break;
                        case BOOLEAN:
                            rowData.add(String.valueOf(cell.getBooleanCellValue()));
                            break;
                        case BLANK:
                            rowData.add("");
                            break;
                        default:
                            rowData.add("");
                    }
                } else {
                    rowData.add("");
                }
            }
            tableData.add(rowData);
        }
        return tableData;
    }

    public static void createTableInWord(XWPFDocument wordDocument, List<List<String>> tableData) {
        if(tableData.isEmpty()) {
            return ;
        }
        XWPFTable table = wordDocument.createTable(tableData.size(), tableData.get(0).size());

        for(int i = 0;i < tableData.size();i++) {
            List<String> rowContent = tableData.get(i);
            XWPFTableRow row = table.getRow(i);

            for(int j = 0;j < rowContent.size();j++) {
                String content = rowContent.get(j);
                XWPFTableCell cell = row.getCell(j);

                if(cell == null) {
                    // 如果单元格为Null，就创建新的单元格
                    cell = row.createCell();
                }

                cell.setText(content);
            }
        }
    }

}
